package com.uni.controllers.editors;

import java.beans.PropertyEditorSupport;
import java.util.HashSet;
import java.util.Set;

import com.uni.db.GenericService;
import com.uni.domain.User;

public class ListEditor extends PropertyEditorSupport {

    private GenericService<User> userService;
    
    public ListEditor(GenericService<User> userService){
    	this.userService = userService;
    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
    	if(text == null){
    		setValue(new HashSet<User>());
    		return;
    	}
    	String[] users = text.split(",");
    	Set<User> students = new HashSet<User>(users.length);
    	for(String user : users){
    		Long id;
    		try {
    			id = Long.parseLong(user);
    		} catch (NumberFormatException e){
    			throw new IllegalArgumentException(e.getMessage());
    		}
			User usr = userService.get(id);
			if(usr != null){
				students.add(usr);
			}
    	}
    	setValue(students);
    }

}
